const Controller = require("egg").Controller;

class NoteController extends Controller {
  // 获取笔记列表
  async getNoteList() {
    const noteList = await this.ctx.service.note.getNoteList();
    this.ctx.body = {
      code: 200,
      data: noteList,
    };
  }

  // 获取用户自己笔记列表
  async getSelfNoteList() {
    try {
      let currentPage = this.ctx.query.currentPage;
      let pageSize = this.ctx.query.pageSize;
      const data = await this.ctx.service.note.getSelfNoteList({
        currentPage,
        pageSize,
      });
      this.ctx.body = {
        code: 200,
        data: data,
      };
    } catch (error) {
      this.ctx.body = {
        code: -1,
        data: null,
        message: error.message,
      };
    }
  }

  async saveNote() {
    const { ctx } = this;
    try {
      const { id, title, content } = ctx.request.body;
      const { id: user_id } = ctx.decode;
      const result = await this.ctx.service.note.saveNote({
        id,
        title,
        content,
        user_id,
      });
      this.ctx.body = {
        code: 200,
        data: result,
      };
    } catch (error) {
      this.ctx.body = {
        code: -1,
        data: null,
        message: error.message,
      };
    }
  }

  // 删除笔记
  async deleteNote() {
    const { ctx } = this;
    try {
      const { id } = ctx.request.body;
      const note = await this.ctx.service.note.deleteNote(id);
      this.ctx.body = {
        code: 200,
        data: note,
      };
    } catch (error) {
      this.ctx.body = {
        code: -1,
        data: null,
        message: error.message,
      };
    }
  }

  //查询笔记
  async findNote() {
    const { ctx } = this;
    try {
      const { id } = ctx.request.body;
      const note = await this.ctx.service.note.findNoteById(id);
      this.ctx.body = {
        code: 200,
        data: note,
      };
    } catch (error) {
      this.ctx.body = {
        code: -1,
        data: null,
        message: error.message,
      };
    }
  }

  //修改笔记
  async modifyNote() {
    const { ctx } = this;
    try {
      const { id: user_id } = ctx.decode;
      const { id, title, content } = ctx.request.body;
      const result = await this.ctx.service.note.modifyNote({
        id,
        title,
        content,
        user_id,
      });
      this.ctx.body = {
        code: 200,
        data: result,
      };
    } catch (error) {
      this.ctx.body = {
        code: -1,
        data: null,
        message: error.message,
      };
    }
  }
}

module.exports = NoteController;
